--- 模块功能：MQTT客户端数据接收处理
-- @author openLuat
-- @module mqtt.mqttInMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)

require "nvm"
require "config"
require "logGenerator"
require "vibrationAlarmLogic"

-- 参数配置文件初始化
nvm.init("config.lua", true)
-- 变量初始化
local clientNo, errInfo, sysTime = nvm.get("info")[1], "", ""

-- 获取震动烈度
local function getIiData(getData)
    local ii, getDataList
    getDataList = string.split(getData, ",")
    local getIiDateList = string.split(getDataList[1], "=")
    if getIiDateList[1] == "Ii" then
        ii = tonumber(getIiDateList[2])
    else
        ii = nil
    end
    return ii
end

--- MQTT客户端数据接收处理
-- @param mqttClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttInMsg.proc(mqttClient)
function proc(mqttClient)
    local result, data, receiveMsg
    while true do
        sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d",
                                os.date("*t").year, os.date("*t").month,
                                os.date("*t").day, os.date("*t").hour,
                                os.date("*t").min, os.date("*t").sec)
        result, data = mqttClient:receive(60000, "APP_SOCKET_SEND_DATA")
        errInfo = ""
        -- 接收到数据
        if result then
            receiveMsg = data.payload
            log.info("receiveMsg:", receiveMsg)

            if data.topic == "KS002641/GET" then
                local ii = getIiData(receiveMsg)
                log.info("ii",ii)
                if ii ~= nil then
                    vibrationAlarmLogic.VibrationAlarm(ii)
                end

            else
                errInfo = errInfo .. "[" .. sysTime .. "]" ..
                              "[订阅主题满足要求:]" ..
                              "接收的主题:" .. data.topic .. "\n"
                logGenerator.generateLogTask(errInfo, "log")
            end
        else
            break
        end
    end
    log.info("MQTT TASK RESULT", result, "MQTT TASK DATA", data)
    return result or data == "timeout" or data == "APP_SOCKET_SEND_DATA"
end
